const TOKEN_KEY = 'user_token'
const USER_INFO_KEY = 'user_info'
const TOKEN_EXPIRE_KEY = 'token_expire_time'
const EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000 // token有效期7天

// 保存用户信息和token
const saveUserInfo = (userInfo, token) => {
  wx.setStorageSync(USER_INFO_KEY, userInfo)
  wx.setStorageSync(TOKEN_KEY, token)
  wx.setStorageSync(TOKEN_EXPIRE_KEY, Date.now() + EXPIRE_TIME)
}

// 获取用户信息
const getUserInfo = () => {
  return wx.getStorageSync(USER_INFO_KEY) || null
}

// 获取token
const getToken = () => {
  const token = wx.getStorageSync(TOKEN_KEY)
  const expireTime = wx.getStorageSync(TOKEN_EXPIRE_KEY)
  
  if (!token || !expireTime || Date.now() >= expireTime) {
    clearUserInfo()
    return null
  }
  
  return token
}

// 清除用户信息
const clearUserInfo = () => {
  wx.removeStorageSync(USER_INFO_KEY)
  wx.removeStorageSync(TOKEN_KEY)
  wx.removeStorageSync(TOKEN_EXPIRE_KEY)
}

// 自动登录
const autoLogin = async () => {
  try {
    const token = getToken()
    if (!token) return false

    // TODO: 调用后端接口验证token有效性
    const response = await wx.request({
      url: 'your_api_url/verify_token',
      header: { 'Authorization': token }
    })

    if (response.data.success) {
      return true
    } else {
      clearUserInfo()
      return false
    }
  } catch (error) {
    console.error('Auto login failed:', error)
    return false
  }
}

module.exports = {
  saveUserInfo,
  getUserInfo,
  getToken,
  clearUserInfo,
  autoLogin
} 